package com.admin.controller;

import java.io.File;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Workbook;

import com.admin.controller.BaseController.Status;
import com.admin.model.Orders;
import com.admin.model.OrdersReturn;
import com.admin.model.Sys_User;
import com.admin.util.Constants;
import com.admin.util.DateUtil;
import com.admin.util.Excel2007Util;
import com.admin.util.Page;
import com.admin.util.UtilTools;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.PathKit;
import com.jfinal.render.JsonRender;

public class OrdersController extends BaseController {
	public static String ORDERS = "/orders";
	public static String ORDERSUNPRO = "/orders/unproOrder?orders.state=1";
	public Log logger = LogFactory.getLog(OrdersController.class);
	// 首页列表
	public void index(){
		try {
			//订单管理  根据来源    有导出按钮 order_export=1&order_source=1
			//订单列表  根据来源    无导出按钮 order_export=0&order_source=1
			//待发货      无来源        有导出按钮 order_export=1&order_source=0&spec_order=1
			//所有订单  无来源        有导出按钮 order_export=1&order_source=0
			//order_export=1 有导出  order_export=0 无导出
			//order_source=1 有来源  order_source=0 无来源
			//spec_order=1  待发货
			//获取当前用户设置的来源
			Sys_User user = getSessionAttr(Constants.LOGIN_USER);
			Sys_User user_new = Sys_User.dao.findById(user.get("id"));
			String sources = user_new.get("sources");
			String afromsources = null;
			String sourceList = null;
			//获取是否有来源和导出功能
			String order_source = this.getPara("order_source");
			String order_export = this.getPara("order_export");
			if(null != sources && sources != ""){
				String[] new_sources = sources.split(",");
				StringBuffer newsource = new StringBuffer();
				for(int i = 0;i<new_sources.length;i++){
					String a = new_sources[i];
					newsource.append("'"+a+"',");
				}
				//来源状态是空或者是0不根据来源查询  如果是1则根据来源查询
				if(order_source==null){
					sourceList = null;
				}else if(Integer.parseInt(order_source)==1){
					sourceList = newsource.substring(0,newsource.length()-1).toString();
				}else{
					sourceList = null;
				}
			}else{
				//如果source为空则没有设置来源
				sourceList = null;
			}
				 
			if(UtilTools.isNotNull(sourceList)){
				afromsources = "source in ("+ sourceList +")";
			}
			
			//处理查询条件
			Orders orders = getModel(Orders.class);
			//根据产品名称
			String pro_name = orders.get("pro_name");
			String apro_name = null;
			if(UtilTools.isNotNull(pro_name)){
				apro_name = "pro_name like '%"+ pro_name +"%'";
			}
			//根据姓名
			String name = orders.get("name");
			String aname = null;
			if(UtilTools.isNotNull(name)){
				aname = "name like '%"+ name +"%'";
			}
			//根据手机号码
			String mobile = orders.get("mobile");
			String amobile = null;
			if(UtilTools.isNotNull(mobile)){
				amobile = "mobile like '%"+ mobile +"%'";
			}
			//根据创建时间
			String createStartDate = getPara("createStartDate");
			String createStartDateQ = null;
			if(UtilTools.isNotNull(createStartDate)){
				createStartDateQ = "create_date >= '"+ createStartDate +"'";
			}
			setAttr("createStartDate",createStartDate);
			String createEndDate = getPara("createEndDate");
			String createEndDateQ = null;
			if(UtilTools.isNotNull(createEndDate)){
				createEndDateQ = "create_date <= '"+ DateUtil.addDay(createEndDate,"yyyy-MM-dd",1) +"'";
			}
			setAttr("createEndDate",createEndDate);
			//根据订单来源
			String source = orders.get("source");
			String asource = null;
			if(UtilTools.isNotNull(source)){
				asource = "source like '%"+ source +"%'";
			}
			//根据订单状态
			Integer state = orders.getInt("state");
			
			//特殊的订单列表  spec_order 如果不为空  链接给定的是什么值就按这个值的状态查询
			Integer spec_order = this.getParaToInt("spec_order");
			if(null != spec_order){
				/*if(Integer.parseInt(spec_order)==1){
					state=1;
				}*/
				state = spec_order;
			}
			String astate = null;
			if(UtilTools.isNotNull(state)){
				astate = "state = '"+ state +"'";
			}
			//根据客户类型
			Integer xian = orders.getInt("xian");
			String axian = null;
			if(UtilTools.isNotNull(xian)){
				astate = "xian = '"+ xian +"'";
			}
			//数据状态为1
			String astatus = "status=1";
			// 处理分页参数
			Page<Orders> page = new Page<Orders>(getPara("pageCurrent"),getPara("pageSize"));
			page.setOrderField("create_date");
			page.setOrderDirection("desc");
			Orders.dao.listByPage(new String[]{apro_name,aname,amobile,asource,astate,axian,createStartDateQ,createEndDateQ,astatus,afromsources},page);
			setAttr("page",page);
			setAttr("pro_name",pro_name);
			setAttr("name",name);
			setAttr("mobile",mobile);
			setAttr("source",source);
			setAttr("state",state);
			setAttr("xian",xian);
			
			//order_export  1有导出显示所有  0无导出隐藏按钮和电话   spec_order  1是待发货
			this.setAttr("order_export",order_export);
			this.setAttr("order_source",order_source);
			this.setAttr("spec_order",spec_order);
			render("/jsp/orders/index.jsp");
		} catch (Exception e) {
			logger.info("发现异常："+e.getMessage());
			e.printStackTrace();
		}
	}
	
	// 跳转到修改
	public void detail(){
		try {
			Integer stat = this.getParaToInt("stat");
			String id = getPara("id");
			Orders orders = Orders.dao.getObject(Long.parseLong(id));
			setAttr("orders", orders);
			this.setAttr("stat",stat);
			render("/jsp/orders/update.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage(), e);
		}
	}
	
	// 保存
	public void save() {
		Integer stat = this.getParaToInt("stat");
		try {
			Orders orders = getModel(Orders.class);
			String time = String.valueOf(new Date().getTime());
			String agordernum = time + (int)(Math.random()*100);
			orders.set("order_no",agordernum);
			if (null == orders.get("id")) {
				orders.save();
			} else {
				orders.update();
			}
			if(stat==null){
				ajax(Status.success,ORDERS,true);
			}else if(stat==1){
				ajax(Status.success,ORDERS,true);
			}else if(stat==2){
				ajax(Status.success,ORDERSUNPRO,true);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage(), e);
			ajax(Status.error,null,null);
		}
	}
	
	// 删除
	public void delete(){
		try {
			String[] ids = getParaValues("ids");
			//假删除
			boolean result = Orders.dao.jiadel(ids);
			if(result){
				ajax(Status.success,null,false);
			}else{
				ajax(Status.error,null,null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajax(Status.error,null,null);
		}
	}
	
	// 会员订单列表
	public void orderList(){
		try {
			//获取该mobile的订单列表
			// 处理查询条件
			String mobile = this.getPara("mobile");
			String aname = null;
			if(UtilTools.isNotNull(mobile)){
				aname = "mobile = '"+ mobile +"'";
			}
			
			//获取该mobile的回访记录
			Page<OrdersReturn> page_return = new Page<OrdersReturn>(getPara("pageCurrent"),getPara("pageSize"));
			page_return.setOrderField("create_date");
			page_return.setOrderDirection("desc");
			OrdersReturn.dao.listByPage(new String[]{aname},page_return);
			setAttr("page_return",page_return);
			
			//数据状态为1
			String astatus = "status=1";
			//获取该mobile的订单列表
			Page<Orders> page_orders = new Page<Orders>(getPara("pageCurrent"),getPara("pageSize"));
			page_orders.setOrderField("create_date");
			page_orders.setOrderDirection("desc");
			Orders.dao.listByPage(new String[]{aname,astatus},page_orders);
			setAttr("page_orders",page_orders);
			this.setAttr("mobile", mobile);
			render("/jsp/orders/ordersList.jsp");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void saveReturns() {
		try {
			String mobile = this.getPara("mobile");
			String content = this.getPara("content");
			OrdersReturn ordersReturn = getModel(OrdersReturn.class);
			Sys_User user = getSessionAttr(Constants.LOGIN_USER);
			ordersReturn.set("loginname", user.get("loginname"));
			ordersReturn.set("create_date",new Date());
			ordersReturn.set("mobile",mobile);
			ordersReturn.set("content", content);
			ordersReturn.save();
			JSONObject obj = new JSONObject();
			obj.put("loginname", user.get("loginname"));
			obj.put("create_date", DateUtil.format(new Date(),"yyyy-MM-dd hh:mm:ss"));
			obj.put("content", content);
			obj.put("mobile", mobile);
			render(new JsonRender(obj).forIE());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage(), e);
			ajax(Status.error,null,null);
		}
	}
	
	// 导出数据
	public void exportExl(){
		try {
			
			//订单管理  根据来源    有导出按钮 order_export=1&order_source=1
			//订单列表  根据来源    无导出按钮 order_export=0&order_source=1
			//待发货      无来源        有导出按钮 order_export=1&order_source=0&spec_order=1
			//所有订单  无来源        有导出按钮 order_export=1&order_source=0
			//order_export=1 有导出  order_export=0 无导出
			//order_source=1 有来源  order_source=0 无来源
			//spec_order=1  待发货
			//获取当前用户设置的来源
			Sys_User user = getSessionAttr(Constants.LOGIN_USER);
			Sys_User user_new = Sys_User.dao.findById(user.get("id"));
			String sources = user_new.get("sources");
			String afromsources = null;
			String sourceList = null;
			//获取是否有来源和导出功能
			String order_source = this.getPara("order_source");
			String order_export = this.getPara("order_export");
			if(null != sources && sources != ""){
				String[] new_sources = sources.split(",");
				StringBuffer newsource = new StringBuffer();
				for(int i = 0;i<new_sources.length;i++){
					String a = new_sources[i];
					newsource.append("'"+a+"',");
				}
				//来源状态是空或者是0不根据来源查询  如果是1则根据来源查询
				if(order_source==null){
					sourceList = null;
				}else if(Integer.parseInt(order_source)==1){
					sourceList = newsource.substring(0,newsource.length()-1).toString();
				}else{
					sourceList = null;
				}
			}else{
				//如果source为空则没有设置来源
				sourceList = null;
			}
				 
			if(UtilTools.isNotNull(sourceList)){
				afromsources = "source in ("+ sourceList +")";
			}
			
			// 处理查询条件
			Orders orders = getModel(Orders.class);
			
			//根据产品名称
			String pro_name = this.getPara("pro_name");
			pro_name = UtilTools.toUtf8(pro_name);
			String apro_name = null;
			if(UtilTools.isNotNull(pro_name)){
				apro_name = "pro_name like '%"+ pro_name +"%'";
			}
			//根据姓名
			String name = this.getPara("name");
			name = UtilTools.toUtf8(name);
			String aname = null;
			if(UtilTools.isNotNull(name)){
				aname = "name like '%"+ name +"%'";
			}
			//根据手机号码
			String mobile = this.getPara("mobile");
			String amobile = null;
			if(UtilTools.isNotNull(mobile)){
				amobile = "mobile like '%"+ mobile +"%'";
			}
			//根据创建时间

			String createStartDate = getPara("createStartDate");
			String createStartDateQ = null;
			if(UtilTools.isNotNull(createStartDate)){
				createStartDateQ = "create_date >= '"+ createStartDate +"'";
			}
			setAttr("createStartDate",createStartDate);
			String createEndDate = getPara("createEndDate");
			String createEndDateQ = null;
			if(UtilTools.isNotNull(createEndDate)){
				createEndDateQ = "create_date <= '"+ DateUtil.addDay(createEndDate,"yyyy-MM-dd",1) +"'";
			}
			setAttr("createEndDate",createEndDate);
			//根据订单来源
			String source = this.getPara("source");
			String asource = null;
			if(UtilTools.isNotNull(source)){
				asource = "source like '%"+ source +"%'";
			}
			
			//根据订单状态
			Integer state = this.getParaToInt("state");
			
			//特殊的订单列表  spec_order 如果不为空  链接给定的是什么值就按这个值的状态查询
			Integer spec_order = this.getParaToInt("spec_order");
			if(null != spec_order){
				/*if(Integer.parseInt(spec_order)==1){
					state=1;
				}*/
				state = spec_order;
			}
			String astate = null;
			if(UtilTools.isNotNull(state)){
				astate = "state = '"+ state +"'";
			}
			//根据客户类型
			Integer xian = this.getParaToInt("xian");
			String axian = null;
			if(UtilTools.isNotNull(xian)){
				axian = "xian = '"+ xian +"'";
			}
			
			//数据状态为1
			String astatus = "status=1";
			List<Orders> list = Orders.dao.exportQuery(new String[]{afromsources,apro_name,aname,amobile,asource,astate,axian,createStartDateQ,createEndDateQ,astatus});
			// 处理要导出的数据
			Workbook wb = Orders.dao.batchExport(list);
			// 导出excel数据
			Excel2007Util.exportExcelData("订单信息", getResponse(), wb);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("导出数据异常");
		}
		renderNull();
	}
	
	/**
	 * 导入订单数据-将会修改原来的订单的状态
	 * @return
	 */
	public void doImport(){
		JSONObject obj = new JSONObject();
		try {
			String fileUrl = getPara("fileUrl");
			fileUrl = PathKit.getWebRootPath()+File.separator+fileUrl;
			String errorMessage = Orders.dao.batchImport(fileUrl);	
			obj.put("msg",errorMessage);
		} catch (Exception e) {
			String message = "导入订单时发生异常:"+e.getMessage();
			e.printStackTrace();
			logger.error(message, e);
			obj.put("msg","导入异常");
		}
		renderJson(obj);
	}
	
	public void unproOrder(){
		try {
			//获取当前用户设置的来源
			/*Sys_User user = getSessionAttr(Constants.LOGIN_USER);
			Sys_User user_new = Sys_User.dao.findById(user.get("id"));
			String sources = user_new.get("sources");
			String[] new_sources = sources.split(",");
			StringBuffer newsource = new StringBuffer();
			for(int i = 0;i<new_sources.length;i++){
				String a = new_sources[i];
				newsource.append("'"+a+"',");
			}
			String ss = newsource.substring(0,newsource.length()-1).toString();
			String afromsources = null;
			if(UtilTools.isNotNull(ss)){
				afromsources = "source in ("+ ss +")";
			}*/
			// 处理查询条件
			Orders orders = getModel(Orders.class);
			//根据产品名称
			String pro_name = orders.get("pro_name");
			String apro_name = null;
			if(UtilTools.isNotNull(pro_name)){
				apro_name = "pro_name like '%"+ pro_name +"%'";
			}
			//根据姓名
			String name = orders.get("name");
			String aname = null;
			if(UtilTools.isNotNull(name)){
				aname = "name like '%"+ name +"%'";
			}
			//根据手机号码
			String mobile = orders.get("mobile");
			String amobile = null;
			if(UtilTools.isNotNull(mobile)){
				amobile = "mobile like '%"+ mobile +"%'";
			}
			//根据创建时间
			String createStartDate = getPara("createStartDate");
			String createStartDateQ = null;
			if(UtilTools.isNotNull(createStartDate)){
				createStartDateQ = "create_date >= '"+ createStartDate +"'";
			}
			setAttr("createStartDate",createStartDate);
			String createEndDate = getPara("createEndDate");
			String createEndDateQ = null;
			if(UtilTools.isNotNull(createEndDate)){
				createEndDateQ = "create_date <= '"+ DateUtil.addDay(createEndDate,"yyyy-MM-dd",1) +"'";
			}
			setAttr("createEndDate",createEndDate);
			//根据订单来源
			String source = orders.get("source");
			String asource = null;
			if(UtilTools.isNotNull(source)){
				asource = "source like '%"+ source +"%'";
			}
			//根据订单状态
			String astate = "state=1";
			
			//根据客户类型
			Integer xian = orders.getInt("xian");
			String axian = null;
			if(UtilTools.isNotNull(xian)){
				axian = "xian = '"+ xian +"'";
			}
			
			// 处理分页参数
			Page<Orders> page = new Page<Orders>(getPara("pageCurrent"),getPara("pageSize"));
			page.setOrderField("create_date");
			page.setOrderDirection("desc");
			Orders.dao.listByPage(new String[]{apro_name,aname,amobile,asource,astate,axian,createStartDateQ,createEndDateQ},page);
			setAttr("page",page);
			setAttr("pro_name",pro_name);
			setAttr("name",name);
			setAttr("mobile",mobile);
			setAttr("source",source);
			setAttr("state",1);
			setAttr("xian",xian);
			render("/jsp/orders/unproOrder.jsp");
		} catch (Exception e) {
			logger.info("发现异常："+e.getMessage());
			e.printStackTrace();
		}
	}
}
